<template>
  <main class="todo-list">
    <ul>
      <draggable v-model="todos" :item-key="(todo) => todo.id">
        <template #item="{ element: todo, index }">
          <li :key="todo.id">
            <input
              type="checkbox"
              :checked="todo.completed"
              @change="completedTodo(index)"
            />
            <input
              type="text"
              :class="{ active: todo.completed }"
              :value="todo.content"
              @blur="handleMod(index, $event.target.value)"
              @keyup.enter="handleMod(index, $event.target.value)"
            />
            <button @click="deleteTodo(index)">删除</button>
          </li>
        </template>
      </draggable>
    </ul>
  </main>
</template>

<script setup>
import draggable from 'vuedraggable';
const todos = defineModel('todos');

// 删除
const deleteTodo = (index) => {
  todos.value.splice(index, 1);
};

// 修改
const handleMod = (index, content) => {
  if (content === '') {
    deleteTodo(index);
  } else {
    todos.value[index].content = content;
  }
};

// 完成
const completedTodo = (index) => {
  todos.value[index].completed = !todos.value[index].completed;
};
</script>

<style scoped>
.todo-list li {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 40px;
  list-style: none;
  border-bottom: 1px solid #eee;
}
.todo-list li input[type='text'] {
  position: relative;
  padding: 5px 0;
  border: none;
  outline: none;
  flex: 1;
  margin-left: 20px;
}

.todo-list li:hover {
  background-color: #eee;
}

.todo-list li:hover input[type='text'] {
  background-color: #eee;
}

.todo-list li input[type='text'].active {
  color: #f77;
  text-decoration: line-through;
}

.todo-list li button {
  padding: 0 10px;
}
</style>
